package com.cw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.JwtConfig;
import com.cw.entity.*;
import com.cw.entity.dto.DishDto;
import com.cw.handler.CustomException;
import com.cw.service.CategoryService;
import com.cw.service.DishFlavorService;
import com.cw.service.DishService;
import com.cw.service.WindowsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private   DishFlavorService dishFlavorService;

    @Autowired
    private WindowsService windowsService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param
     * @return
     */

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody DishDto dishDto, HttpServletRequest request){
        //查询内容
        log.info("添加的菜品为：{}",dishDto);
        dishService.saveWithFlavors(dishDto,request);

        //清理所有菜品的缓存数据
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success(null);
    }

    /**
     * 分页查询
     * @param page 分页数
     * @param pageSize 每页大小
     * @param name 条件
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam(name = "page") Integer page,
                  @RequestParam(name = "pageSize") Integer  pageSize,
                  @RequestParam(name = "name",required = false) String name, HttpServletRequest request){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);

        //1.构建分页
        Page<Dish> dishPage = new Page(page, pageSize);
        //2.构建条件
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.like( name!=null,Dish::getName,name);
        dishWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        if(!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            Employee employee=(Employee)this.redisTemplate.opsForHash().get("EMP",JwtConfig.getCurrentId(request));
            dishWrapper.eq(Dish::getWindowId,employee.getWindowId());
        }
        dishService.page(dishPage,dishWrapper);

        //3.定义一个page<DishDto>
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //4.把原来分页的参数copy到新建的参数上
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");


        //5.数据项copy
        List<DishDto> dishDtoList = dishPage.getRecords().stream().map(item -> {
            DishDto dishDto = new DishDto();
            //基本数据值拷贝
            BeanUtils.copyProperties(item, dishDto);
            //构建一个查询，去查一个分类的名称
            Category category = categoryService.getById(item.getCategoryId());
            String windowName = windowsService.getById(item.getWindowId()).getWindowName();
            dishDto.setCategoryName(category.getName());
            dishDto.setWindowName(windowName);
            return dishDto;
        }).collect(Collectors.toList());

        //5.1 把dishDtoList数据封装到dishDtopage的 records 属性上
        dishDtoPage.setRecords(dishDtoList);

        log.info("返回的数据:{}",dishDtoPage);
        //返回数据dishDtoPage
        return R.success(dishDtoPage);
    }

    /**
     * 回显编辑内容
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public  R  getById(@PathVariable Long id){
        log.info("菜品的id为：{}",id);
        DishDto dishDto =  dishService.getByIdWithFlavor(id);
        return  R.success(dishDto);
    }

    @PutMapping
    public  R update(@RequestBody DishDto dishDto){
        log.info("dishDto:{}",dishDto);

       R res= dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return res;
    }


    /**
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public  R  getDishByCategoryId(Dish dish){
        log.info("查询的菜品:{}",dish);

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

        //
        List<DishDto> dishDtoList1;
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList1 = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList1 != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList1);
        }

        //创建dto集合
        List<DishDto> dishDtoList = new ArrayList<>();

        for (Dish d : list) {
            DishDto dishDto = new DishDto();
            //拷贝基本数据
            BeanUtils.copyProperties(d,dishDto);
            //查询条件
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(d.getId()!=null,DishFlavor::getDishId,d.getId());
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            //把口味添加进去
            dishDto.setFlavors(flavors);

            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return   R.success(dishDtoList);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam  List<Long> ids){
        log.info("删除的属性为：{}",ids);

        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        wrapper.eq("status",1);
        int count = dishService.count(wrapper);
        if (count>0){
            throw  new CustomException("当前菜品在售无法删除");
        }

        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 批量起售
     * status = 将要修改的状态
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatusByBatch(@PathVariable Integer status, @RequestParam(name = "ids") List<Long> ids){
        log.info("status：{}，ids：{}", status,ids);

        List<Dish> list = dishService.listByIds(ids);
        List<Dish> dishList = list.stream().map(item -> {
            item.setStatus(status);
            dishService.updateById(item);
            return item;
        }).collect(Collectors.toList());


        return R.success(dishList);
    }
}
